﻿@using KPIS.GERP.Models.ICM.ViewModel
@using KPIS.GERP.Models.ICM
@model GatheringPR

@{
    ViewBag.Title = "สร้างคำขอซื้อ/จ้าง";
    ViewBag.Descr = ViewBag.Title + " เพื่อทำการขอซื้อ/จ้างโดยหน่วยงานพัสดุ";
    var allPprItem = new KPIS.GERP.WEB.GIMS.PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient()
        .Select(new PrePurchaseRequestItem(), new[] { "PrePurchaseRequest.Priority" });
    PrePurchaseRequest ppr = null;
    var tasks = new KPIS.GERP.WEB.GIMS.SysApprovalService.SysApprovalServiceClient().SelectTask();
    var LookUpService = new KPIS.GERP.WEB.GIMS.IcmMasLookUpService.IcmMasLookUpServiceClient();
    var durCountSelectList = LookUpService.MasLookUpSelectList(KPIS.GERP.Models.ICM.IcmMasLookUpType.LookUpType.DurationCount);
}

@using (Html.BeginForm("Create", "PrePurchaseItem", FormMethod.Post, new { @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()
    <div id="loading">
        <div id="loadingcontent">
            <p id="loadingspinner">
                Loading...
            </p>
        </div>
    </div>
    <p id="message"></p>
    <div class="block-button-menu-above">
        @Html.ButtonViewAll()
        @Html.ButtonSubmit()
    </div>

    if (Model.PrePurchaseRequestItem != null)
    {
        var a = Model.PrePurchaseRequestItem;
        var b = Model.PrePurchaseRequestItem.GroupBy(o => o.MasResourceItem != null ? o.MasResourceItem.Name : o.MasBudgetExpense.Name);
        var c = Model.PrePurchaseRequestItem.GroupBy(o => o.PprId);
        var d = Model.PrePurchaseRequestItem.Select(o => o.MasResourceItem != null ? o.MasResourceItem.Name : o.MasBudgetExpense.Name);
        <div class="row-fluid">
            <div class="alert alert-block alert-success">
                กรุณายืนยันการเลือกรายการ (รายการที่รวบรวมมามีทั้งหมด @a.Count รายการพัสดุ /
                @b.Count() รายการพัสดุที่แตกต่าง /
                @c.Count() แจ้งความประสงค์)
            </div>
        </div>

        <div class="row-fluid">
            <table border="1" id="table" class="table table-striped table-bordered table-hover" aria-describedby="table_info">
                <thead>
                    <tr>
                        <th class="center" style="width:50px;">
                            <!-- Check box delete multiple records column-->
                            <label>
                                <input type="checkbox" id="checkbox100" checked="checked" />
                                <span class="lbl"></span>
                            </label>
                        </th>
                        <th style="text-align: center;">
                            @Html.DisplayName("รายการค่าใช้จ่าย")
                        </th>
                        <th style="text-align: center;">
                            @Html.DisplayName("รายละเอียด")
                        </th>
                        <th style="text-align: center;">
                            @Html.DisplayName("แหล่งเงิน")
                        </th>
                        <th style="text-align: center;">
                            @Html.DisplayNameFor(model => model.PrePurchaseRequestItem.FirstOrDefault().Qty)
                        </th>
                        <th style="text-align: center;">
                            @Html.DisplayNameFor(model => model.PrePurchaseRequestItem.FirstOrDefault().Price)
                        </th>
                        <th style="text-align: center;">
                            @Html.DisplayNameFor(model => model.PrePurchaseRequestItem.FirstOrDefault().Amount)
                        </th>
                        <th style="text-align: center;">
                            @Html.DisplayNameFor(model => model.PrePurchaseRequestItem.FirstOrDefault().CreatedWhen)
                        </th>

                        @*<th style="text-align: center; width: 40px">
                                แยกรายการย่อยใน PR
                            </th>*@
                    </tr>
                </thead>

                <tbody>
                    @foreach (var m in Model.PrePurchaseRequestItem.OrderBy(o => o.PprId))
                    {
                        if ((ppr == null || ppr.PprId != m.PprId) &&
                            (ppr = (from ppri in allPprItem
                                    where ppri.PprId == m.PprId
                                    select ppri.PrePurchaseRequest).FirstOrDefault()) != null)
                        {
                            <tr>
                                <td colspan="8">
                                    <b>
                                        <a target="_blank" href='@Url.Action("Details", "PrePurchase", new { Id = m.PprId })'>
                                            @(string.IsNullOrWhiteSpace(m.PrePurchaseRequest.Code) ? "ไม่ระบุ" : m.PrePurchaseRequest.Code)
                                            -
                                            @Html.DisplayFor(model => m.PrePurchaseRequest.Name)
                                            (ยอดรวม @((allPprItem.Where(o => o.PprId == ppr.PprId).Sum(o => o.Amount) ?? 0).ToString("#,##0.00")) บาท)
                                        </a>
                                    </b>
                                    @if (ppr.Priority.LookUpName != "ปกติ")
                                    {
                                        <font color="red">
                                            @ppr.Priority.LookUpName
                                        </font>
                                    }
                                    &nbsp;<i>
                                        ต้องการใช้ภายใน
                                        @if (ppr.DurTypeId == 10)
                                        {
                                            var durCountSelectListItem = durCountSelectList
                                                .FirstOrDefault(o => o.Value == (ppr != null ? Convert.ToString(ppr.DurCountId) : ""));
                                            var durCountWording = durCountSelectListItem == null ? string.Empty : durCountSelectListItem.Text;
                                            var task = tasks
                                                .OrderByDescending(o => o.TaskId)
                                                .FirstOrDefault(o => o.RefId == ppr.PprId && o.AppPrcId == 6);
                                            @*:[@m.PrePurchaseRequest.RequireDuration.Value]*@
                                            if (ppr.DurCountId == 10) //วันที่สร้างรายการ
                                            {
                                                if (ppr.CreatedWhen.HasValue)
                                                {
                                                    @* @: (วันที่สร้างรายการ คือ @ppr.CreatedWhen.Value.ToString("dd MMM yyyy"))
                                                        @:@Html.DisplayFor(model => m.PrePurchaseRequest.RequireDuration) วัน นับจาก @durCountWording*@
                                                    @ppr.CreatedWhen.Value.AddDays(m.PrePurchaseRequest.RequireDuration.Value).ToString("dd MMM yyyy")
                                                }
                                            }
                                            else if (ppr.DurCountId == 11) // วันที่ยืนยันรายการ - ส่งขออนุมัติรายการ
                                            {
                                                if (task != null && task.CreatedWhen.HasValue)
                                                {
                                                    @*@: (วันที่ยืนยันรายการ คือ @task.CreatedWhen.Value.ToString("dd MMM yyyy"))*@
                                                    @task.CreatedWhen.Value.AddDays(m.PrePurchaseRequest.RequireDuration.Value).ToString("dd MMM yyyy")
                                                }
                                            }
                                            else if (ppr.DurCountId == 12) // วันที่อนุมัติรายการ
                                            {
                                                if (task != null && task.ApprovedWhen.HasValue)
                                                {
                                                    @*@: (วันที่อนุมัติรายการ คือ @task.ApprovedWhen.Value.ToString("dd MMM yyyy"))*@
                                                    @task.ApprovedWhen.Value.AddDays(m.PrePurchaseRequest.RequireDuration.Value).ToString("dd MMM yyyy")
                                                }
                                            }
                                            @:&nbsp;
                                                                                }
                                        else
                                        {
                                            @:วันที่ @(ppr.RequireDate != null ? ppr.RequireDate.Value.ToString("dd MMM yyyy") : "")
                                                                                }
                                    </i>



                                    @Html.HiddenFor(model => m.PprItemId)
                                    @Html.ValidationMessageFor(model => m.PprItemId)
                                </td>
                            </tr>
                        }
                        <tr>
                            <td class="center">
                                <!-- Check box all for delete multiple records -->
                                <label>
                                    <input type="checkbox" name="selectIds" checked="checked" value="@(m.PprItemId)" @*((m.PprItemId != null) ? "checked=\"checked\"" : "")*@ />
                                    <span class="lbl"></span>
                                </label>
                            </td>
                            <td>
                                @Html.DisplayFor(model => m.MasBudgetExpense.Name)
                            </td>
                            <td width="200px">
                                @(m.MasResourceItem != null ? " - " : "")
                                @Html.DisplayFor(model => m.MasResourceItem.Name)
                                @Html.Raw((m.Descr ?? "").Replace("\n", "<br/>"))
                            </td>
                            <td style="text-align: center;">
                                @Html.DisplayFor(model => m.MasBudgetSource.Name)
                            </td>
                            <td style="text-align: center;">
                                @((m.Qty ?? 0).ToString("#,##0.##"))
                            </td>
                            <td style="text-align: right;">
                                @Html.DisplayFor(model => m.Price)
                            </td>
                            <td style="text-align: right;">
                                @Html.DisplayFor(model => m.Amount)
                            </td>
                            <td style="text-align: center;">
                                @Html.DisplayFor(model => m.CreatedWhen)
                            </td>
                            @*<td class="center">
                                                                @{ var mk = (m.MasResourceItem != null ? m.MasResourceItem.Name : m.MasBudgetExpense.Name); }
                                                                @if (d.Count(o => o == mk) > 1)
                                {
                                    <label title="ซ้ำ @d.Count(o => o == mk) รายการ">
                                        <input type="checkbox" name="selectIdsToPreventCombind" value="@(m.PprItemId)" />
                                        <span class="lbl"></span>
                                    </label>
                                }
                                                            </td>*@
                        </tr>
                    }
                </tbody>
            </table>

        </div>

        <hr />


        <div class="widget-box">
            <div class="widget-header header-color-blue2">
                <h4 class="lighter smaller">สร้างคำขอซื้อ/จ้าง (รหัสซื้อจ้างต่อไป @KPIS.GERP.Models.Class.CodeGenerate.GetNextCode(CodeGenerate.TransectionType.PurchaseRequest))</h4>
            </div>

            <div class="widget-body">
                <div class="widget-body-inner">
                    <div class="widget-main">
                        <div class="form-horizontal">
                            <div class="control-group">
                                <div class="control-label">
                                    @Html.DisplayName("วิธีการจัดหา")
                                </div>
                                <div class="controls">
                                    @Html.DropDownListFor(model => model.PurchaseRequest.PcMethodId, (IEnumerable<SelectListItem>)ViewBag.purchaseMethod)
                                    @* @Html.DropDownListFor(model => model.PurchaseRequest.PcMethodId, new KPIS.GERP.WEB.GIMS.IcmMasterService.IcmMasterServiceClient().SelectListPurchaseMethod(null, false), "เลือกวิธีการจัดหา")  *@
                                    @Html.Raw("&nbsp<font color=red>*</font>")
                                    @Html.ValidationMessageFor(model => model.PurchaseRequest.PcMethodId)
                                </div>
                            </div>
                            <div class="control-group">
                                <div class="control-label">
                                    @Html.DisplayName("เหตุผลที่เลือก")
                                </div>
                                <div class="controls">
                                    @Html.TextAreaFor(model => model.PurchaseRequest.PcMethodReason)
                                    @Html.Raw("&nbsp<font color=red>*</font>")
                                    @Html.ValidationMessageFor(model => model.PurchaseRequest.PcMethodReason)
                                </div>
                            </div>
                            <div class="control-group">
                                <div class="control-label">
                                    @Html.DisplayName("หมายเหตุ")
                                </div>
                                <div class="controls">
                                    @Html.TextAreaFor(model => model.PurchaseRequest.Remark)
                                    @Html.Raw("&nbsp<font color=red>*</font>")
                                    @Html.ValidationMessageFor(model => model.PurchaseRequest.Remark)
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    }
}

@section scripts
{
    <style type="text/css">
        #loading {
            display: none;
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            z-index: 1000;
        }

        #loadingcontent {
            display: table;
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        }

        #loadingspinner {
            display: table-cell;
            vertical-align: middle;
            width: 100%;
            text-align: center;
            font-size: larger;
            padding-top: 80px;
        }
    </style>

    <script src="~/Content/Ace/assets/js/spin.min.js"></script>
    <script>

        $(function () {
            $('table th input:checkbox').on('click', function () {
                var that = this;
                $(this).closest('table').find('tr > td:first-child input:checkbox')
                    .each(function () {
                        this.checked = that.checked;
                        $(this).closest('tr').toggleClass('selected');
                    });
            });
        });

        $("form").not("#formsearch").submit(function (e) {
            e.preventDefault();
            var currentForm = this;
            bootbox.confirm("ท่านต้องการยืนยัน ใช่หรือไม่", function (result) {
                if (result) {
                    // currentForm.submit();
                    $.ajax({
                        beforeSend: function () {
                            $("#loading").fadeIn();
                            var opts = {
                                lines: 12, // The number of lines to draw
                                length: 7, // The length of each line
                                width: 4, // The line thickness
                                radius: 10, // The radius of the inner circle
                                color: '#000', // #rgb or #rrggbb
                                speed: 1, // Rounds per second
                                trail: 60, // Afterglow percentage
                                shadow: false, // Whether to render a shadow
                                hwaccel: false // Whether to use hardware acceleration
                            };
                            var target = document.getElementById('loading');
                            var spinner = new Spinner(opts).spin(target);
                            // $(target).data('spinner', spinner);
                        },
                        url: "Create",
                        type: "post",
                        dataType: "json",
                        data: $(currentForm).serialize(),
                        success: function (result) {
                            if (result.success) {
                                window.location = "@Url.Action("Index")";
                                //$("#loading").hide();
                            } else {

                                $("#message").html(result.message);
                                $("#loading").hide();
                            }
                        }
                    });
                }
            });

        });
    </script>
}